package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import io.lettuce.core.dynamic.output.CodecAwareOutputFactoryResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private IElderService elderService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInConfigService checkInConfigService;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //检验老人是否已经入住
        //select * from elder where id_card_no = #{idCardNo} and status = 1
        Elder one = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                // 状态
                .one();
        //判断老人是否已经入住如果入住则抛出异常
        if (one != null && one.getStatus() == 1) {
            throw new RuntimeException("该老人已入住");
        }

        //更新床位状态为已入住
        //update bed set bed_status = 1 where id = #{bedId}
        /*方法一*/
//        bedService.lambdaUpdate()
//                .set(Bed::getBedStatus, 1)
//                .eq(Bed::getId, dto.getCheckInConfigDto().getBedId())
//                .update();
        /*方法二*/
        Bed bed = new Bed();
        // 设置状态
        bed.setBedStatus(1);
        // 设置id
        bed.setId(dto.getCheckInConfigDto().getBedId());
        // 更新
        bedService.updateById(bed);

        //根据bedid 查询bed
        Bed dbBed = bedService.getById(dto.getCheckInConfigDto().getBedId());
        if (dbBed == null){
            throw new RuntimeException("床位不存在");
        }


        //新增或更新老人
        Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        newElder.setStatus(1);
        newElder.setBedNumber(dbBed.getBedNumber());
        newElder.setBedId(dbBed.getId());
      //  elderService.saveOrUpdate(newElder);//这个对象的id如果在数据库中存在则更新，不存在则插入
        if ( newElder.getId() == null ) {
            elderService.save(newElder);
        } else {
            elderService.updateById(newElder);
        }

        //新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(newElder.getId());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(newElder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(newElder.getId());
        checkIn.setElderName(newElder.getName());
        checkIn.setBedNumber(dbBed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        this.save(checkIn);

        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);

    }


}
